# -*- coding: utf-8 -*-
"""
__mktime__ = '2019/4/13'
__author__ = 'Just'
__filename__ = 'user'
"""
from flask import jsonify, g, request

from app.libs.error_code import DeleteSuccess, ParameterException, Success, ForbiddenException, NotFoundException
from app.libs.redprint import Redprint
from app.libs.token_auth import auth
from app.model.user import User, db


api = Redprint('user')


@api.route('', methods=['GET'])
@auth.login_required
def get_user():
    """
    用户查找自己的信息
    :return:
    """
    uid = g.user.uid    # g.user 认证后存储了客户端的信息
    user = User.query.filter_by(id=uid).first_or_404(msg='用户不存在', error_code=6001)
    return jsonify(user)


@api.route('', methods=['POST'])
@auth.login_required
def revise_user():
    """
    修改我的信息
    :return:
    """
    uid = g.user.uid    # g.user 认证后存储了客户端的信息
    new_params = request.get_json()
    if not new_params:
        raise ParameterException(msg='请上传新数据')
    user = User.query.filter_by(id=uid).first_or_404(msg='用户不存在', error_code=6001)
    with db.auto_commit():
        if new_params['nickname']:
            user.nickname = new_params['nickname']
    return Success(code=201, msg='修改成功')


@api.route('', methods=['DELETE'])
@auth.login_required
def delete_user():
    """删除自己的用户信息 这个方法一般不提供"""
    uid = g.user.uid
    with db.auto_commit():
        user = User.query.filter_by(id=uid).first_or_404(msg='用户不存在', error_code=6001)
        user.delete()  # 软删除
    return DeleteSuccess()
